<?php

class importexport_type_excel_reader {

    private $rowopen = null;

    public function xmlToArray($xml) {
        $parser = xml_parser_create();
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
        xml_parse_into_struct($parser, $xml, $tags);
        xml_parser_free($parser);
        
        return $tags;
    }

    public function getRowXml($lineXml) {
        if ($this->rowopen) {
            $this->xml .= $lineXml;
        } else {
            $this->xml = $lineXml;
        }
        
        $data = $this->xmlToArray($this->xml);
        
        foreach ((array) $data as $value) {
            if ($this->rowopen != true && $value['tag'] == 'Row' && $value['type'] == 'open') {
                $this->rowopen = true;
            }
            
            if ($this->rowopen == true && $value['tag'] == 'Row' && $value['type'] == 'close') {
                $this->rowopen = false;
            }
        }
        
        if ($this->rowopen === true || $this->rowopen === null) {
            $return = true;
        } else {
            $this->rowopen = null;
            $return = $data;
        }
        
        return $return;
    }

    public function getRowData($data) {
        $row = array();
        $index = 0;
        foreach ((array) $data as $value) {
            if ($cellopen != true && $value['tag'] == 'Cell' && $value['type'] == 'open') {
                $cellopen = true;
                if ($value['attributes']['ss:Index']) {
                    for ($index; $index < ($value['attributes']['ss:Index'] - 1); $index++) {
                        $row[$index] = '';
                    }
                }
                $index = $value['ss:Index'] ? ($value['ss:Index'] - 1) : $index;
            }
            
            if ($cellopen == true && $value['tag'] == 'Cell' && $value['type'] == 'close') {
                $cellopen = false;
                $index++;
            }
            if (($cellopen == true || $value['tag'] == 'Cell') && $value['type'] == 'complete') {
                if ($value['attributes']['ss:Type'] == 'Number') {
                    $value['value'] = $value['value'];
                } elseif ($value['attributes']['ss:Type'] == 'Boolean') {
                    $value['value'] = $value['value'] ? 'true' : 'false';
                }
                $row[$index] .= $value['value'] ? $value['value'] : '';
                
                if ($value['tag'] == 'Cell')
                    $index++;
            }
        }
        
        return $row;
    }
}
